import { jsSdkAuth } from '~/services/config';

let wx = window.wx;
const url = window.location.href.split('#')[0];

const share = {
  title: '健康双节，好礼送四亿',
  desc: '汤臣倍健好礼送四亿，过不一样的双节！',
  link: url,
  imgUrl: 'http://images.4000916916.com/yyj/2016/thirdAct/03share.jpg',
};

export const isWechat = /MicroMessenger/.test(navigator.userAgent);

export function shareTimeline() {
  wx.onMenuShareTimeline(share);
}

export function shareAppMessage() {
  wx.onMenuShareAppMessage(share);
}

export function config() {
  if (!isWechat) {
    return Promise.resolve();
  }
  return jsSdkAuth({
    url,
    appId: __DEV__ ? 'wxb425b33623e260d4' : 'wx2f995336548675b4',
  })
    .then(rs => {
      // try set global varibale
      if (!wx) wx = window.wx;

      wx.config({
        debug: false,
        appId: rs.appId,
        timestamp: rs.timestamp,
        nonceStr: rs.nonceStr,
        signature: rs.signature,
        jsApiList: [
          'showMenuItems',
          'hideMenuItems',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'scanQRCode',
        ],
      });

      wx.ready(() => {
        shareTimeline();
        shareAppMessage();
      });
    });
}

export function scanQRCode(type) {
  return new Promise(resolve => {
    wx.scanQRCode({
      needResult: 1,
      scanType: [...type],
      success(res) {
        resolve(res.resultStr);
      },
    });
  });
}

export function close() {
  try {
    wx.closeWindow();
    return true;
  } catch (e) {
    return false;
  }
}

export default {};
